package com.yyw.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yyw.bean.Employee;
import com.yyw.utils.BaseContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {

    //注入session对象
//    @Autowired
//    private HttpSession session;


    /**
     *插入元对象字段填充（用于插入时对公共字段的填充）
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        //告诉mybatisplus 什么字段，赋什么值。
                //  参数一：具体的字段名字，名字不能乱写，必须是属性的名字
                //  参数二： 具体赋的值
        metaObject.setValue("createTime" , LocalDateTime.now());
        metaObject.setValue("updateTime" , LocalDateTime.now());

        //从session对象里面取曾经登录的时候，保存的员工对象
/*        Employee e = (Employee) session.getAttribute("employee");
        metaObject.setValue("createUser" ,e.getId());
        metaObject.setValue("updateUser" ,e.getId());*/
        //
        //使用springsecurity改造，设置员工id到threadlocal中，方便在公共字段填充时拿值
        Employee e = (Employee) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("e = " + e);

        metaObject.setValue("createUser" , e.getId());
        metaObject.setValue("updateUser" ,e.getId());


    }


    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        metaObject.setValue("updateTime" , LocalDateTime.now());

        //从session对象里面取曾经登录的时候，保存的员工对象
       /* Employee e = (Employee) session.getAttribute("employee");
        metaObject.setValue("updateUser" ,e.getId());*/
        Employee e = (Employee) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("e = " + e);

        metaObject.setValue("updateUser" ,e.getId());
    }
}
